package han.chensing.latos.common.level.util;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class StreamUtil {
    public static String fromException(Exception e)
        throws IOException {
        StringWriter writer=new StringWriter();
        PrintWriter printWriter=new PrintWriter(writer);
        e.printStackTrace(printWriter);
        writer.close();
        printWriter.close();
        return writer.toString();
    }

    public static void streamCopy(InputStream from, OutputStream to) throws IOException{
        byte[] bytes=new byte[2048];
        int read;
        while((read=from.read(bytes))!=-1)
            to.write(bytes,0,read);
    }

    public static String readStringFromFile(File file) throws IOException{
        FileInputStream fileInputStream=new FileInputStream(file);
        InputStreamReader inputStreamReader=new InputStreamReader(
                fileInputStream, StandardCharsets.UTF_8);
        StringBuilder stringBuilder=new StringBuilder();
        char[] chars=new char[512];
        int read;
        while((read=inputStreamReader.read(chars,0,chars.length))!=-1){
            stringBuilder.append(chars,0,read);
        }
        inputStreamReader.close();
        fileInputStream.close();
        return stringBuilder.toString();
    }

    public static byte[] getFileStreamBytes(File file) throws IOException{
        FileInputStream fileInputStream=new FileInputStream(file);
        byte[] streamBytes = getStreamBytes(fileInputStream);
        fileInputStream.close();
        return streamBytes;
    }

    public static byte[] getStreamBytes(InputStream inputStream) throws IOException{
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        streamCopy(inputStream,byteArrayOutputStream);
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        return byteArray;
    }

    public static String getSuffix(String name){
        int i = name.lastIndexOf('.');
        if (i==-1)return null;
        return name.substring(i+1);
    }
}
